import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/entity/UserTouchBar.dart';
import 'package:mahjong/entity/card/MahjongCardEntity.dart';
import 'package:mahjong/entity/mahjong/MahjongInfoEntity.dart';
import 'package:mahjong/notify/CurrentUserInfo.dart';
import 'package:mahjong/widget/CurrentGameCommons.dart';
import 'package:mahjong/widget/MahjongCommon.dart';
import 'package:provider/provider.dart';

class BillClearing extends StatefulWidget {
  final String title, description;
  final Image image;

  BillClearing({
    @required this.title,
    @required this.description,
    this.image,
  });
  @override
  _BillClearingState createState() => _BillClearingState();
}

class _BillClearingState extends State<BillClearing> {
  @override
  Widget build(BuildContext context) {
    return Consumer2(builder: (BuildContext buildContext,
        MahjongInfoEntity roomProvider,
        CurrentUserInfo userProvider,
        Widget child) {
      if (roomProvider.billClearingInfo == null) {
        return SizedBox();
      }

      return (roomProvider.state != null &&
              roomProvider.showBillHistory &&
              !userProvider.prepare)
          ? Dialog(
              insetPadding: null,
              /*  shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(Consts.padding),
              ), */
              elevation: 0.0,
              backgroundColor: Colors.black.withOpacity(0.8),
              child: dialogContent(context, roomProvider),
            )
          : SizedBox();
    });
  }

  dialogContent(BuildContext context, MahjongInfoEntity roomProvider) {
    return Stack(
      children: <Widget>[
        buildCard(context, roomProvider),
        //buildCircle(),
      ],
    );
  }

  Widget buildCard(BuildContext context, MahjongInfoEntity roomProvider) {
    List<Widget> items = [];
    items.add(Text(
      "========${widget.title}========",
      style: TextStyle(
        fontSize: 18.sp,
        fontWeight: FontWeight.w700,
      ),
    ));
    items.add(SizedBox(height: 5.h));

    if (null != roomProvider.billClearingInfo) {
      roomProvider.billClearingInfo.forEach((item) {
        items.add(buildUserBill(item));
      });
    }

    return Positioned(
      top: Consts.padding,
      left: Consts.padding,
      right: Consts.padding,
      bottom: Consts.padding,
      child: Container(
        padding: EdgeInsets.only(
          //top: Consts.avatarRadius + Consts.padding,
          //bottom: Consts.avatarRadius + Consts.padding,
          left: Consts.avatarRadius + Consts.padding,
          right: Consts.avatarRadius + Consts.padding,
        ),
        margin: EdgeInsets.only(top: Consts.avatarRadius),
        decoration: new BoxDecoration(
          color: Colors.white,
          shape: BoxShape.rectangle,
          border: Border.all(color: Colors.grey.withOpacity(0.2), width: 10.00),
          borderRadius: BorderRadius.circular(Consts.padding),
          boxShadow: [
            BoxShadow(
              color: Colors.black26,
              blurRadius: 10.0,
              offset: const Offset(0.0, 10.0),
            ),
          ],
        ),
        child: Stack(
          children: [
            Column(
              mainAxisSize: MainAxisSize.min, // To make the card compact
              children: items,
            ),
            Align(
              alignment: new Alignment(0, 1),
              child: Container(
                height: 30.h,
                width: 150.w,
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.resolveWith((states) {
                      //设置按下时的背景颜色
                      if (states.contains(MaterialState.pressed)) {
                        return Colors.blue[200];
                      }
                      //默认不使用背景颜色
                      return Colors.green;
                    }),
                    elevation: MaterialStateProperty.all(12),
                    shape: MaterialStateProperty.all(StadiumBorder()),
                  ),
                  child: Text(
                    roomProvider.state != RoomState.OVER ? '下一局' : "游戏结束",
                    style: TextStyle(fontSize: 16.sp),
                  ),
                  onPressed: () {
                    MahjongInfoEntity roomInfo =
                        Provider.of<MahjongInfoEntity>(context, listen: false);
                    roomInfo.nextGame(roomProvider.state != RoomState.OVER);
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  List<Widget> buildTouchBar(List<UserTouchBar> data, double cardWidth) {
    if (data == null) {
      return [];
    } else {
      List<Widget> param = [];
      data.forEach((element) {
        List<Widget> cards = [];
        for (int i = 0, j = element.cards.length; i < j; i++) {
          MahjongCardEntity cardEntity = element.cards[i];
          if (j == 4 && i < j - 1 && element.cardEnum == CardEnum.ANGANG) {
            cardEntity.cardId = null;
            cards.add(CardWidget.buildExportCard(cardEntity, cardWidth));
          } else if (j == 4 &&
              i == j - 1 &&
              element.cardEnum == CardEnum.ANGANG) {
            cards.add(CardWidget.buildExportCard(cardEntity, cardWidth));
          } else {
            cards.add(CardWidget.buildExportCard(cardEntity, cardWidth));
          }
        }
        param.add(Padding(
            padding: EdgeInsets.only(left: cardWidth / 2),
            child: Row(
              children: cards,
            )));
      });
      return param;
    }
  }

  Container buildUserBill(BillClearingInfo billInfo) {
    String userImageSrc;
    try {
      userImageSrc =
          diskPartUserProvider[billInfo.userInfo.userId].sysUser.portraitUrl;
    } catch (e) {
      print("用户未初始化...");
    }
    double itemHeight = 50.h;
    // 头像的高度 为 整体item 的高度  90%
    return Container(
      margin: EdgeInsets.only(bottom: 10.h),
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      height: itemHeight,
      decoration: BoxDecoration(
          color: Colors.grey.withOpacity(0.4),
          borderRadius: BorderRadius.circular(Consts.padding)),
      child: Row(
        children: [
          Container(
            width: itemHeight,
            height: itemHeight,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ClipOval(
                    child: MahjongCommon.headerImage(userImageSrc,
                        width: itemHeight / 2, height: itemHeight / 2)),
                Text(
                  billInfo.userInfo.userId,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 13.sp),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                )
              ],
            ),
          ),
          Expanded(
              child: billInfo.winState
                  ? Container(
                      height: itemHeight,
                      child: Image.asset(
                        "images/mahjong/commons/" +
                            billInfo.userWinSeq.toString() +
                            "hu.png",
                        height: double.infinity,
                      ),
                    )
                  : SizedBox(),
              flex: 2),
          Expanded(
              flex: 8,
              child: Container(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Text(
                            billInfo.fractionResources.join(" "),
                            style: TextStyle(fontSize: 13.sp),
                            maxLines: 1,
                          )),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Expanded(
                              child: SingleChildScrollView(
                                  scrollDirection: Axis.horizontal,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: billInfo.userCards
                                            .map((e) =>
                                                CardWidget.buildExportCard(
                                                    MahjongCardEntity(
                                                        cardId: e),
                                                    itemHeight / 3))
                                            .toList(),
                                      ),
                                      Row(
                                          children: buildTouchBar(
                                              billInfo.cardTouchBars,
                                              itemHeight / 3)),
                                    ],
                                  ))),
                          Container(
                            width: itemHeight / 3 * 3,
                            child: billInfo.huCard == null
                                ? SizedBox()
                                : Row(
                                    children: [
                                      SizedBox(
                                        width: itemHeight / 3 * 2,
                                      ),
                                      CardWidget.buildExportCard(
                                          MahjongCardEntity(
                                              cardId: billInfo.huCard),
                                          itemHeight / 3)
                                    ],
                                  ),
                          )
                        ],
                      )
                    ]),
              )),
          Expanded(
              child: Text(
                billInfo.fraction.toString(),
                textAlign: TextAlign.end,
                style: TextStyle(
                    color: Colors.red,
                    fontWeight: FontWeight.w500,
                    fontSize: 20.sp),
              ),
              flex: 1),
        ],
      ),
    );
  }
}

class Consts {
  Consts._();

  static const double padding = 16.0;
  static const double avatarRadius = 16.0;
}
